//
//  ZMUserInfo.m
//  基本框架
//
//  Created by runone02 on 2018/6/29.
//  Copyright © 2018年 liqiyun. All rights reserved.
//

#import "ZMUserInfo.h"

static ZMUserInfo *_userInfo;
@implementation ZMUserInfo

//用户信息的单列
+ (instancetype) shareUserInfo{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _userInfo = [[ZMUserInfo alloc]init];
    });
    return _userInfo;
}


//是否登录
- (BOOL) isLogin{
    return self.userId.length && self.sessionToken.length;
}

//返回性别
- (NSString *)sexName{
    NSString *string = nil;
    if (self.sex == 0 ) {
        string = @"未知";
    }else if (self.sex == 1 ){
        string = @"女";
    }else{
        string = @"男";
    }
    return string;
}

//保存用户信息到沙盒
- (void) saveUserInfoToSandbox{
    NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:self.sessionToken forKey:userSessionToken];
    [defaults synchronize];
}

//从沙盒中加载用户信息
- (void) loadUserInfoFromSanbox{
    self.sessionToken = [[NSUserDefaults standardUserDefaults]objectForKey:userSessionToken];
}

//解析用户信息
- (void) loadUserInfo:(AVObject *)user{
    if (user) {
        self.userId = user.objectId;
        self.sessionToken = ((AVUser *)user).sessionToken;
        self.userName = ((AVUser *)user).username;
        self.email = ((AVUser *)user).email;
        self.emaiVerfied = [user[@"emailVerified"] boolValue];
        self.thumb = user[@"thumb"];
        self.sex = [user[@"sex"]integerValue];
        self.signature = user[@"signature"];
    }
}

- (void)updateUserInfo:(AVObject *)user{
    if ([user isKindOfClass:[AVObject class]]) {
        self.userId = user[@"objectId"];
        self.userName = user[@"username"];
        self.email = user[@"email"];
        self.emaiVerfied = [user[@"emaiVerfied"] boolValue];
        self.thumb = user[@"thumb"];
        
        self.sex = [user[@"sex"] integerValue];
        self.signature = user[@"signature"];
    }
}

/**
 退出登录
 */
- (void)loginOut{
    self.userId = nil;
    self.userName = nil;
    self.sessionToken = nil;
    self.email = nil;
    self.emaiVerfied = nil;
    self.thumb = nil;
    self.signature = nil;
    [self saveUserInfoToSandbox];
    
}
@end
